import pygame
from pygo1963.view.gui import Desktop, ContenedorMovil
import threading
from pygo1963.view.GoBoard import GoBoard

import gui
from gui import Button
from pygo1963.view import defaultStyle
from pygo1963.view.constants import BACK_PATH

class View():
    """ 
    Class that wrapps pygame view code. Associated with the view is a 
    controller object. 
    """
    
    def __init__(self):
        self.screen = pygame.display.set_mode((800, 600), pygame.DOUBLEBUF)
        self.clock = pygame.time.Clock()
        self.run = True
        self.back = pygame.image.load(BACK_PATH).convert()
        self.desktop = Desktop()
        
        defaultStyle.init(gui)
        self.gui = gui
        
        self.controller = Controller()
    
    def update(self):
        
        self.desktop.update()
    
    def draw(self):    
        self.screen.fill((20, 40, 50))
        self.screen.blit(self.back, (0, 0))
        self.desktop.draw()


class GameView():
    """ View class that represents a running game. """
    
    def __init__(self, view, game):
        
        self.game = game
        self.controller = view.controller
        #ugly
        view.controller = Controller()
        
        win = ContenedorMovil(position=(230, 50), size=(550, 530), parent=view.desktop)
        
        pass_button = Button(position = (400, 10), size=(60, 0),parent = win, text="Pass")
        pass_button.onClick = self.controller.pass_game
        
        win.onClick = self.controller.on_click
        win.onMouseDown = self.capture_first_position
        win.first_position = pygame.mouse.get_pos() 
        win.board = GoBoard(parent=win, position=(0, 80), delta=(30, 40), game=game)        
        win.board.windows = win
        win.board.controller = view.controller
        
        thread = threading.Thread(target=game.play)
        thread.start()
        
        win.onClose = self.finish_game
    
    def finish_game(self, window):
        
        #Avoid deadlock of game waiting for human move
        self.game.finish()
        self.controller.is_listening = False
        
    
    def capture_first_position(self, button):
        button.first_position = pygame.mouse.get_pos()

class Controller:
    
    def __init__(self):
        self.is_listening = False
        self.position = None
    
    def get_stone_position(self, posicion, board):
    
        if (posicion[0] < board.delta[0] or posicion[1] < board.delta[1]):
            return (-1, -1)
        
        x = posicion[0] - board.delta[0] - board.empty_size_x
        y = posicion[1] - board.delta[1] - board.empty_size_y
        
        pos_x = x / board.dx
        pos_y = y / board.dy
        
        pos_x += 0.5
        pos_y += 0.5
        
        return (int(pos_x) + 1, int(pos_y) + 1)

    def check_window_not_moved(self, first_position, last_position):
    
        deltaX, deltaY = first_position[0] - last_position[0], first_position[1] - last_position[1]
        
        if (deltaX < 0):
            deltaX = -1 * deltaX
        
        if (deltaY < 0):
            deltaY = -1 * deltaY
            
        return not (deltaX > 5 or deltaY > 5)
    
    def transform_coordinates(self, posRaton, posContenedor):
    
        x1, x2 = posRaton[0], posContenedor[0]
        y1, y2 = posRaton[1], posContenedor[1] 
        
        if (x2 < 0):
            x1 -= x2
            x2 = 0
            
        if (y2 < 0):
            y1 -= y2
            y2 = 0    
        
        return x1 - x2, y1 - y2 
    
    #FIXME Esto es una bazofia
    def invert_coordinates(self, nueva_ficha, window):
        y = window.board.game.board.size - nueva_ficha[1]
        x = nueva_ficha[0] - 1
        return (x, y) 
    
    def pass_game(self, window):
        if self.is_listening:
            self.position = (-1,-1)
            self.is_listening = False
            
    def on_click(self, window):
        if self.is_listening:
                 
            mouse_pos = pygame.mouse.get_pos()    
            if self.check_window_not_moved(window.first_position, mouse_pos):
                coordinates = self.transform_coordinates(mouse_pos, window.position)
               
                nueva_ficha = self.get_stone_position(coordinates, window.board)
                    
                if nueva_ficha != (-1, -1):    
                    nueva_ficha = self.invert_coordinates(nueva_ficha, window)
                        
                    self.position = nueva_ficha
                    self.is_listening = False